<template>
  <div>
    <div ref="chart" :class="className" :style="{height:height,width:width}" />
  </div>
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons')
import resize from '../../mixins/resize'

export default {
  components: {
  },
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler() {
        this.query()
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    query() {
      this.chart.clear()
      const ret = this.chartData
      const xAxisData = ret.map(item => item.medicineName)
      const seriesData = ret.map(item => item.medicineCount)
      this.setOptions({
        xAxisData,
        seriesData
      })
    },
    initChart() {
      this.chart = echarts.init(this.$refs.chart, 'macarons')
      this.setOptions()
    },
    setOptions({ xAxisData = [], seriesData } = {}) {
      this.chart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '51px',
          right: '80px',
          containLabel: true
        },
        title: {
          text: '药品销售排行Top10',
          bottom: '4',
          left: 'center',
          textStyle: {
            color: '#999'
          }
        },
        xAxis: [
          {
            type: 'category',
            data: xAxisData,
            axisLabel: {
              rotate: 50,
              color: '#999',
              formatter: value => {
                const maxLen = 6
                if (value.length > maxLen) {
                  return value.substring(0, maxLen)
                }
                return value
              }
            }
          }
        ],
        yAxis: [
          {
            nameTextStyle: {
              color: '#999'
            },
            axisLabel: {
              color: '#999'
            },
            name: '销售量'
          }
        ],
        series: [
          {
            name: '销售量',
            type: 'bar',
            data: seriesData
          }
        ]
      })
    }
  }
}
</script>
